<template>
  <div class="detail">
    <!--基本信息-->
    <staff-basic-info
      :url="url"
      :departmentList="departmentList"
      v-if="load"
      :positionList="positionList"
      :staffId="staffId"
      :selectEnums="selectEnums.nice_inner_user"
      :baseInfo="detail"
      @refreshData="getStaffDetail"
    ></staff-basic-info>
    <!--教学信息-->
    <teach-base-info
      :selectEnums="selectEnums.nice_teacher_info"
      :url="url"
      :staffId="staffId"
      :teachingInfo="teachingInfo"
      @refreshData="getStaffTeachInfo('info')"
      v-if="!isSalesOrOperation && load && isTeachingInfo"
    ></teach-base-info>
    <!--学管信息-->
    <teach-management-info
      :selectEnums="selectEnums.nice_teacher_info"
      :url="url"
      :staffId="staffId"
      :teachingInfo="tutorInfo"
      @refreshData="getStaffTeachInfo('info')"
      v-if="
        !isSalesOrOperation &&
          load &&
          isTeachingInfo &&
          detail.user_type == '4' &&
          tutorInfo
      "
    ></teach-management-info>
    <!--教师资格证信息-->
    <teacher-certificate-info
      :selectEnums="selectEnums.nice_teacher_cert"
      v-if="!isSalesOrOperation && isTeachingCertificate && load"
      :url="url"
      :staffId="staffId"
      :teacherCert="teacherCertificate"
      @refreshData="getStaffTeachInfo('cert')"
    ></teacher-certificate-info>
    <div class="border" v-if="!isSalesOrOperation && load && isExperience">
      <h3>教学经历</h3>
    </div>
    <nice-table
      :data="teachingList"
      :showIndex="true"
      :columns="teachingColumns"
      :pagination="teachingPagination"
      v-if="!isSalesOrOperation && load && isExperience"
    ></nice-table>
    <div class="border" v-if="!isSalesOrOperation && load && isClass">
      <h3>班级信息</h3>
    </div>
    <nice-table
      :data="classList"
      :showIndex="true"
      :columns="classColumns"
      :pagination="classPagination"
      v-if="!isSalesOrOperation && load && isClass"
    ></nice-table>
    <div class="border" v-if="!isSalesOrOperation && load && isCourseWare">
      <h3>课件信息</h3>
    </div>
    <nice-table
      :data="courseList"
      :showIndex="true"
      :columns="courseColumns"
      :pagination="coursePagination"
      v-if="!isSalesOrOperation && load && isCourseWare"
    >
      <el-table-column
        label="操作"
        align="center"
        width="100"
        slot="opreation"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button size="small" type="text" @click="viewCourse(scope.row)"
            >查看</el-button
          >
        </template>
      </el-table-column>
    </nice-table>
    <div class="border" v-if="!isSalesOrOperation && load && isCourse">
      <h3>题目信息</h3>
    </div>
    <nice-table
      :data="topicList"
      :showIndex="true"
      :columns="topicColumns"
      :pagination="topicPagination"
      v-if="!isSalesOrOperation && load && isCourse"
    >
      <el-table-column
        label="操作"
        align="center"
        width="100"
        slot="opreation"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button size="small" type="text" @click="viewCourse(scope.row)"
            >查看</el-button
          >
        </template>
      </el-table-column>
    </nice-table>
    <div class="border" v-if="isSalesOrOperation && load">
      <h3>学校信息</h3>
    </div>
    <nice-table
      :data="schoolList"
      :showIndex="true"
      :columns="schoolColumns"
      :pagination="schoolPagination"
      v-if="load && isSalesOrOperation"
    ></nice-table>
  </div>
</template>
<script>
import { ossUpload, manageTree, getInfoByTutor } from "@/api/api.js";
import {
  getStaffDetail,
  getTeachExperienceById,
  getClassInfoByTutorId,
  getStaffTeachInfo,
  getCourseWare,
  getSchoolBySalesId,
  getByOperationId,
  findEnumTreeByTableNameAndFieldName
} from "@/api/user";
import StaffBasicInfo from "./components/staff-basic-info";
import TeachBaseInfo from "./components/teach-base-info";
import teachManagementInfo from "./components/teach-management-info";
import TeacherCertificateInfo from "./components/teacher-certificate-info";
import { myEnumsMixins } from "@/utils/mixins";
export default {
  name: "staff-detail",
  components: {
    StaffBasicInfo,
    TeachBaseInfo,
    TeacherCertificateInfo,
    teachManagementInfo
  },
  mixins: [myEnumsMixins],
  data() {
    return {
      url: "",
      departmentList: [],
      isSales: false,
      isSalesOrOperation: false,
      isTeachingInfo: false,
      isTeachingCertificate: false,
      isExperience: false,
      isClass: false,
      load: false,
      isCourseWare: false,
      isCourse: false,
      positionList: [],
      detail: {},
      staffId: "",
      teacherCertificate: {},
      teachingList: [],
      classList: [],
      courseList: [],
      topicList: [],
      schoolList: [],
      teachingInfo: {},
      tutorInfo: {},
      teachingColumns: [
        {
          label: "课程名称",
          prop: "name"
        },
        {
          label: "期次",
          prop: "sort",
          width: "80"
        },
        {
          label: "状态",
          prop: "status",
          width: "80"
        },
        {
          label: "上课时间",
          prop: "periodTime",
          width: "500"
        },
        {
          label: "已完成",
          prop: "complete",
          width: "80"
        },
        {
          label: "班级数量",
          prop: "class_num",
          width: "80"
        },
        {
          label: "学生数量",
          prop: "student_num",
          width: "80"
        }
      ],
      classColumns: [
        {
          label: "班级名称",
          prop: "classes_name"
        },
        {
          label: "班级人数",
          prop: "number",
          width: "80"
        },
        {
          label: "课程名称",
          prop: "course_name"
        },
        {
          label: "主讲",
          prop: "teacher_name",
          width: "80"
        },
        {
          label: "期次",
          prop: "sort",
          width: "80"
        },
        {
          label: "状态",
          prop: "status",
          width: "80"
        },
        {
          label: "上课时间",
          prop: "periodTime",
          width: "500"
        },
        {
          label: "课时",
          prop: "complete",
          width: "60"
        }
      ],
      courseColumns: [
        {
          label: "课件名称",
          prop: "name"
        },
        {
          label: "上传时间",
          prop: "create_time"
        },
        {
          label: "关联课程",
          prop: "course_name"
        },
        {
          label: "下载次数",
          prop: "download_num"
        }
      ],
      topicColumns: [
        {
          label: "教材版本",
          prop: "sex"
        },
        {
          label: "年级/科目",
          prop: "sex"
        },
        {
          label: "题目数量",
          prop: "sex"
        },
        {
          label: "引用次数",
          prop: "sex"
        },
        {
          label: "使用次数",
          prop: "sex"
        }
      ],
      schoolColumns: [
        {
          label: "学校名称",
          prop: "school_name",
          extends: [
            {
              clickFunction: val => {
                this.viewSchoolDetail(val);
              }
            }
          ]
        },
        {
          label: "所属地区",
          prop: "region"
        },
        {
          label: "学校等级",
          prop: "level",
          extends: [
            {
              filterFunction: val => {
                return this.$filterEnums(
                  val,
                  this.selectEnums.nice_school.level
                );
              }
            }
          ]
        },
        {
          label: "学校性质",
          prop: "school_type",
          extends: [
            {
              filterFunction: val => {
                return this.$filterEnums(
                  val,
                  this.selectEnums.nice_school.school_type
                );
              }
            }
          ]
        },
        {
          label: "覆盖年级",
          prop: "coverage_grade"
        },
        {
          label: "学生规模",
          prop: "student_scale",
          extends: [
            {
              filterFunction: val => {
                return this.$filterEnums(
                  val,
                  this.selectEnums.nice_school.student_scale
                );
              }
            }
          ]
        },
        {
          label: "校长姓名",
          prop: "school_head_name"
        }
      ],
      teachingPagination: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        handleCurrentChange: this.handleTeachingCurrentChange,
        handleSizeChange: this.handleTeacherSizeChange
      },
      classPagination: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        handleCurrentChange: this.handleClassCurrentChange,
        handleSizeChange: this.handleClassSizeChange
      },
      coursePagination: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        handleCurrentChange: this.handleCourseCurrentChange,
        handleSizeChange: this.handleCourseSizeChange
      },
      topicPagination: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        handleCurrentChange: this.handleTopicCurrentChange,
        handleSizeChange: this.handleTopicSizeChange
      },
      schoolPagination: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        handleCurrentChange: this.handleSchoolCurrentChange,
        handleSizeChange: this.handleSchoolSizeChange
      }
    };
  },
  activated() {
    this.$store.dispatch("common/saveRegion");
    this.url = this.$http.adornUrl(
      `/questionlib/sys/oss/upload?token=${this.$cookie.get("token")}`
    );
    this.staffId = this.$route.params.id;
    this.isSalesOrOperation = false;
    this.getDepartmentList();
  },
  methods: {
    async getStaffTeachInfo(type) {
      this.isTeachingInfo = true;
      this.isTeachingCertificate = true;
      let res = await getStaffTeachInfo({
        table_name: type === "info" ? "nice_teacher_info" : "nice_teacher_cert",
        user_id: this.staffId
      });
      if (res[0]) {
        return;
      }
      let data = res[1];
      if (data && data.code === 0) {
        if (type === "info") {
          this.teachingInfo = data.data ? data.data : { code: 400 };
          this.getByTutor();
        } else {
          this.teacherCertificate = data.data ? data.data : { code: 400 };
        }
      } else {
        this.$message.error(res[1].msg);
      }
    },
    async getByTutor() {
      let param = { tutor_id: this.$route.params.id };
      let res = await getInfoByTutor(param);
      console.log("res111", res);
      if (res[0]) {
        return;
      }
      let data = res[1];
      if (data && data.code === 0) {
        this.tutorInfo = data.data.list.length
          ? data.data.list[0]
          : {
              allocationStatus: "",
              currentStudent: "",
              designateStatus: 1,
              grade: "",
              id: "",
              qrCode: "",
              starNum: "",
              studentUpper: "",
              subject: "",
              tutorId: this.$route.params.id,
              tutorType: ""
            };
        console.log("this.tutorInfo", this.tutorInfo);
      } else {
        this.$message.error(res[1].msg);
      }
    },
    async getDepartmentList() {
      let res = await manageTree({
        tableName: "nice_organization"
      });
      if (res[0]) {
        return;
      }
      let data = res[1];
      if (data && data.code === 0) {
        let list = [];
        if (data.data) {
          list.push({
            label: data.data.Name,
            value: data.data.id,
            parent: data.data.Parent
          });
          if (data.data.child && data.data.child.length) {
            list[0].children = [];
            this.departmentList = [this.queryList(data.data.child, list[0])];
          }
        }
        this.getPositionList();
      }
    },
    queryList(tdata, list) {
      tdata.forEach((ele, index) => {
        list.children.push({
          label: ele.Name,
          value: ele.id,
          parent: ele.Parent
        });
        if (ele.child && ele.child.length) {
          list.children[index].children = [];
          this.queryList(ele.child, list.children[index]);
        }
      });
      return list;
    },
    async getStaffDetail() {
      let res = await getStaffDetail({ "nice_user_base.id": this.staffId });
      if (res[0]) {
        return;
      }
      let data = res[1];
      this.isSalesOrOperation = false;
      this.isTeachingInfo = false;
      this.isTeachingCertificate = false;
      this.isExperience = false;
      this.isClass = false;
      this.isCourseWare = false;
      this.isCourse = false;
      if (data && data.code === 0) {
        this.detail = data.data;
        this.load = true;
        if (
          this.schoolColumns[this.schoolColumns.length - 1].prop === "user_name"
        ) {
          this.schoolColumns.pop();
        }
        this.selectEnums.sys_user.user_type.forEach(ele => {
          if (+ele.real_value === this.detail.user_type) {
            if (
              ele.display_value === "市场人员" ||
              ele.display_value === "运营人员"
            ) {
              this.isSalesOrOperation = true;
              this.isSales = ele.display_value === "市场人员";
              this.schoolColumns.push({
                label: this.isSales ? "运营负责人" : "销售负责人",
                prop: "user_name"
              });
              this.getSchoolList();
            } else if (
              ele.display_value === "主讲老师" ||
              ele.display_value === "辅导老师" ||
              ele.display_value === "课研老师"
            ) {
              this.isSalesOrOperation = false;
              this.getStaffTeachInfo("info"); // 教学
              this.getStaffTeachInfo("cert"); // 教师资格证
              if (ele.display_value === "主讲老师") {
                this.getTeachExperienceById(); // 教学经历
              } else if (ele.display_value === "辅导老师") {
                this.isClass = true;
                this.getClassInfoByTutorId(); // 班级
              } else {
                this.isCourseWare = true;
                this.isCourse = true;
                this.getCourseWare(); // 课件
                this.getCourseList(); // 题目
              }
            }
          }
        });
      } else {
        this.$message.error(res[1].msg);
      }
    },
    async getCourseList() {},
    async getPositionList() {
      let res = await findEnumTreeByTableNameAndFieldName({
        tableName: "nice_inner_user",
        fieldName: "position_id"
      });
      if (res[0]) {
      }
      let data = res[1];
      if (data && data.code === 0) {
        let array = [data.data];
        let response = [];
        this.positionsQueryList(array, response);
        this.positionList = this.$deepcopy(response);
        this.getStaffDetail();
      } else {
        this.$message.error(data.msg);
      }
    },
    positionsQueryList(tdata, list) {
      if (tdata.length) {
        tdata.forEach((ele, index) => {
          list[index] = {
            label: ele.display_value,
            value: ele.t_id,
            parent: ele.parent
          };
          let arr = [];
          this.positionsQueryList(ele.child, arr);
          if (arr.length) {
            list[index].children = arr;
          }
        });
      }
    },
    // 分页获取教学经历
    async getTeachExperienceById() {
      this.isExperience = true;
      let res = await getTeachExperienceById({
        "nice_course_period.teacher_id": this.staffId,
        "page.currPage": this.teachingPagination.pageNum,
        "page.pageSize": this.teachingPagination.pageSize
      });
      if (res[0]) {
        return;
      }
      let data = res[1];
      if (data && data.code === 0) {
        if (data.data.pageList) {
          this.teachingPagination.total = data.data.pageList.totalCount;
          this.teachingList = data.data.pageList.list;
          this.teachingList.forEach(ele => {
            ele.complete = ele.complete_num + "/" + ele.total_num;
            ele.status =
              ele.complete_num === ele.total_num ? "已结课" : "授课中";
            let frequency = JSON.parse(ele.frequency);
            let week = "周" + this.$filterFrequency(frequency);
            ele.periodTime =
              ele.start_date.substring(0, 10) +
              "~" +
              ele.end_date.substring(0, 10) +
              week;
            ele.sort = "第" + this.$convertNum(ele.sort) + "期";
          });
        }
      } else {
        this.$message.error(res[1].msg);
      }
    },
    // 分页获取班级信息
    async getClassInfoByTutorId() {
      let res = await getClassInfoByTutorId({
        "nice_classes.tutor_id": this.staffId,
        "page.currPage": this.classPagination.pageNum,
        "page.pageSize": this.classPagination.pageSize
      });
      if (res[0]) {
        return;
      }
      let data = res[1];
      if (data && data.code === 0) {
        if (data.data.pageList) {
          this.classPagination.total = data.data.pageList.totalCount;
          this.classList = data.data.pageList.list;
          this.classList.forEach(ele => {
            ele.status =
              ele.complete_num === ele.total_num ? "已结课" : "授课中";
            ele.complete = ele.complete_num + "/" + ele.total_num;
            let frequency = JSON.parse(ele.frequency);
            let week = "周" + this.$filterFrequency(frequency);
            ele.periodTime =
              ele.start_date.substring(0, 10) +
              "~" +
              ele.end_date.substring(0, 10) +
              week;
            ele.sort = "第" + this.$convertNum(ele.sort) + "期";
          });
        }
      } else {
        this.$message.error(res[1].msg);
      }
    },
    // 分页获取课件信息
    async getCourseWare() {
      let res = await getCourseWare({
        "nice_course_ware.upload_user_id": this.staffId,
        "page.currPage": this.coursePagination.pageNum,
        "page.pageSize": this.coursePagination.pageSize
      });
      if (res[0]) {
        return;
      }
      let data = res[1];
      if (data && data.code === 0) {
        if (data.data.pageList) {
          this.coursePagination.total = data.data.pageList.totalCount;
          this.courseList = data.data.pageList.list;
        }
      } else {
        this.$message.error(res[1].msg);
      }
    },
    // 分页获取销售学校信息
    async getSchoolList() {
      let arg = {
        "nice_school.user_id": this.staffId,
        "page.currPage": this.schoolPagination.pageNum,
        "page.pageSize": this.schoolPagination.pageSize
      };
      let res = this.isSales
        ? await getSchoolBySalesId(arg)
        : await getByOperationId(arg);
      if (res[0]) {
        return;
      }
      let data = res[1];
      if (data && data.code === 0) {
        if (data.data.pageList) {
          this.schoolPagination.total = data.data.pageList.totalCount;
          this.schoolList = data.data.pageList.list;
          this.schoolList.forEach(ele => {
            let region = this.$filterRegion(
              { province: +ele.province, city: +ele.city, area: +ele.area },
              this.$store.state.common.regions
            );
            ele.region = region[0] + region[1] + region[2];
            let coveragegrade = [];
            ele.nursery_grade && coveragegrade.push("幼儿园");
            ele.junior_grade && coveragegrade.push("小学");
            ele.middle_grade && coveragegrade.push("初中");
            ele.high_grade && coveragegrade.push("高中");
            if (coveragegrade && coveragegrade.length) {
              ele.coverage_grade = coveragegrade.join(",");
            } else {
              ele.coverage_grade = "";
            }
          });
        }
      } else {
        this.$message.error(res[1].msg);
      }
    },
    handleTeachingCurrentChange(val) {
      this.teachingPagination.pageNum = val;
      this.getTeachExperienceById();
    },
    handleTeacherSizeChange(val) {
      this.teachingPagination.pageSize = val;
      this.getTeachExperienceById();
    },
    handleClassCurrentChange(val) {
      this.classPagination.pageNum = val;
      this.getClassInfoByTutorId();
    },
    handleClassSizeChange(val) {
      this.classPagination.pageSize = val;
      this.getClassInfoByTutorId();
    },
    handleCourseCurrentChange(val) {
      this.coursePagination.pageNum = val;
      this.getCourseWare();
    },
    handleCourseSizeChange(val) {
      this.coursePagination.pageSize = val;
      this.getCourseWare();
    },
    handleTopicCurrentChange(val) {
      this.topicPagination.pageNum = val;
    },
    handleTopicSizeChange(val) {
      this.topicPagination.pageSize = val;
    },
    handleSchoolCurrentChange(val) {
      this.schoolPagination.pageNum = val;
      this.getSchoolList();
    },
    handleSchoolSizeChange(val) {
      this.schoolPagination.pageSize = val;
      this.getSchoolList();
    },
    viewCourse(row) {
      window.location.href = row.links;
    },
    viewSchoolDetail(row) {
      this.$router.push({
        name: "school-detail",
        params: { id: row.id }
      });
    },
    async uploadBaseInformationImg(e) {
      let formData = new FormData();
      formData.append("file", e.file);
      let res = await ossUpload(formData, "STAFF_PORTRAIT");
      if (res[0]) {
        return;
      }
      this.detail.imageUrl = res[1].data.url;
    }
  }
};
</script>
<style lang="scss" scoped>
.detail {
  margin-bottom: 50px;
}
</style>
